using System;
using System.Diagnostics;
using System.Globalization;
using System.Resources;
using System.Web.UI;
using newtelligence.DasBlog.Runtime;
using newtelligence.DasBlog.Util;
using newtelligence.DasBlog.Web.Core;

namespace newtelligence.DasBlog.Web
{
    public partial class LogDateBar : UserControl
    {
        // date navigation
        protected ResourceManager resmgr;

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            resmgr = ApplicationResourceTable.Get();

            if (!Page.IsPostBack)
            {
                DateTime dt = new DateTime(DateTime.Now.Year, 1, 1);
                DateTime filteredDate = DateTime.UtcNow;
                string date = null;

                if (Request.QueryString["date"] != null)
                {
                    date = Request.QueryString["date"];

                    try
                    {
                        filteredDate = DateTime.ParseExact(date, "yyyy-MM-dd", CultureInfo.InvariantCulture);
                    }
                    catch (FormatException ex)
                    {
                        ErrorTrace.Trace(TraceLevel.Error, ex);
                    }
                }

                // move the local/non-local date logic to one place
                if (((SharedBasePage) Page).SiteConfig.AdjustDisplayTimeZone && date == null)
                {
                    WindowsTimeZone tz =
                        ((SharedBasePage) Page).SiteConfig.GetConfiguredTimeZone();
                    filteredDate = tz.ToLocalTime(filteredDate);
                }

                // someone is trying to mess with us, let's play along
                if (filteredDate.Year > dt.Year || filteredDate.Year < dt.Year - 11)
                {
                    dt = new DateTime(filteredDate.Year, 1, 1);
                }

                for (int i = 0; i > -12; i--)
                {
                    DropDownListYear.Items.Add(dt.AddYears(i).ToString("yyyy"));
                }

                try
                {
                    DropDownListYear.SelectedValue = filteredDate.Year.ToString();
                }
                catch (ArgumentOutOfRangeException)
                {
                    //TODO: tried to set a year in the future, that's not in the list.
                }

                for (int i = 0; i < 12; i++)
                {
                    DropDownListMonth.Items.Add(dt.AddMonths(i).ToString("MMMM"));
                }

                DropDownListMonth.SelectedIndex = filteredDate.Month - 1;

                int numDays =
                    DateTime.DaysInMonth(Convert.ToInt32(DropDownListYear.SelectedItem.Text),
                                         DropDownListMonth.SelectedIndex + 1);

                for (int i = 1; i <= numDays; i++)
                {
                    DropDownListDay.Items.Add(i.ToString());
                }

                DropDownListDay.SelectedIndex = filteredDate.Day - 1;

                // set the href for for the links
                DateTime nextDate = filteredDate.AddDays(1);
                DateTime previousDate = filteredDate.AddDays(-1);
                DateTime today = DateTime.Now;

                string requestUrl = Context.Request.Path;
                string dateFormat = "{0}?date={1:yyyy-MM-dd}";

                linkNext.HRef = String.Format(CultureInfo.InvariantCulture, dateFormat, requestUrl, nextDate);
                linkPrevious.HRef = String.Format(CultureInfo.InvariantCulture, dateFormat, requestUrl, previousDate);
                linkToday.HRef = String.Format(CultureInfo.InvariantCulture, dateFormat, requestUrl, today);
            }

            DataBind();
        }

        protected override void OnInit(EventArgs e)
        {
            buttonGo.Click += buttonGo_Click;
            base.OnInit(e);
        }

        private void DropDownChanged()
        {
            string requestUrl = Context.Request.Path;
            string month = (DropDownListMonth.SelectedIndex + 1).ToString();
            string day = DropDownListDay.SelectedItem.Text;

            if (month.Length == 1)
            {
                month = "0" + month;
            }

            if (day.Length == 1)
            {
                day = "0" + day;
            }

            string responseUrl =
                String.Format("{0}?date={1}-{2}-{3}", requestUrl, DropDownListYear.SelectedItem, month, day);
            Context.Response.Redirect(responseUrl);
        }

        private void buttonGo_Click(object sender, EventArgs e)
        {
            DropDownChanged();
        }
    }
}